package com.COMP3111H.project;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class New_User_Registration extends Activity implements View.OnClickListener {
	final int HELP = 0;
	// String html_Headline =
	// "<u>Please fill in the information below to register.</u>";
	String strMissingInfoWarning = "Missing required information. Please try again.";

	String strReminder = "<html><body>" + "<p align=\"justify\" size=\"7\"> "
			+ "<font size=\"2\" color=\"#8e8b8b\"> "
			+ "A <b>confirmation email</b> "
			+ "will be sent to you after this registration.</font><p/> "

			+ "<p align=\"justify\">" + "<font size=\"2.2\" color=\"#8e8b8b\">"
			+ "The email contains your " + "<b>initialized password.</b> "
			+ "You can change your password in your next login."
			+ "</font></p>" + "</body></html>";

	Button register, back;
	// TextView missingInfoWarning;
	WebView reminder;
	EditText account, phoneNum;
	Button menu;

	private ProgressDialog progDialog;
	private ProgressThread progThread;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_user_registration);
		initialize();

		register.setOnClickListener(this);
		back.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();

			}
		});

		menu = (Button) findViewById(R.id.registration_menu);
		
		menu.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				 String[] choices={"Home","Help","Cancel"};  
				             AlertDialog dialog = new AlertDialog.Builder(New_User_Registration.this)  
				                     // .setIcon(android.R.drawable.btn_star)  
				                      .setTitle("Menu")  
				                      .setItems(choices, onselect).create();  
				             dialog.show();  
			}
		});
	}
	
	OnClickListener onselect = new OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			Intent myIntent;
			switch (which) {
			case 0:
				myIntent = new Intent(New_User_Registration.this, Home.class);
				startActivity(myIntent);
				break;
			case 1:
				myIntent = new Intent(New_User_Registration.this, Help.class);
				startActivity(myIntent);
				break;
			case 2:
				dialog.dismiss();
				break;
			}
		}
	};

	private void initialize() {
		register = (Button) findViewById(R.id.b_NewUserRegistration_Register);

		account = (EditText) findViewById(R.id.et_NewUserRegistration_Account);
		phoneNum = (EditText) findViewById(R.id.et_NewUserRegistration_Phone);

		// missingInfoWarning = (TextView)
		// findViewById(R.id.tv_NewUserRegistration_Reminder);

		// missingInfoWarning.setText(Html.fromHtml(strReminder));

		back = (Button) findViewById(R.id.b_NewUserRegistration_Back);
		reminder = (WebView) findViewById(R.id.wv_NewUserRegistration_Reminder);
		reminder.loadData(strReminder, "text/html", "utf-8");
	}

	public void onClick(View v) {
		// Missing required information:
		/*
		 * if ( this.missing_info() ){ warning.setText( Html.fromHtml(
		 * html_Warning_Missing));
		 * 
		 * } else if ( this.duplicate_user() ){ warning.setText( Html.fromHtml(
		 * html_Warning_Missing)); } Intent myIntent = new Intent(this,
		 * Home.class); startActivity(myIntent);
		 */

		

		String username = account.getText().toString();
		if (this.missing_info()) {
			Toast.makeText(New_User_Registration.this, strMissingInfoWarning,
					Toast.LENGTH_SHORT).show();
			// warning.setText( Html.fromHtml( html_Warning_Missing,
			// Toast.LENGTH_SHORT));

		} else if (checkEmailAddress(username)) {
			if (!NetworkUtility.inputCheck(username))
				Toast.makeText(
						New_User_Registration.this,
						"There are special characters that are not allowed in your request",
						Toast.LENGTH_SHORT).show();
			else {
				showDialog(0);
				String phoneNumber = phoneNum.getText().toString();
				progThread = new ProgressThread(handler, username, phoneNumber);
				progThread.start();

			}
		} else {
			Toast.makeText(New_User_Registration.this, "Invalid Email address",
					Toast.LENGTH_SHORT).show();
		}

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 0:
			progDialog = new ProgressDialog(this);
			progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progDialog.setMessage("Registering...");
			return progDialog;
		default:
			return null;
		}
	}

	final Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			removeDialog(0);
			String returnResult = msg.getData().getString("returnResult");
			if (returnResult.contains("insert_new_user_successful")) {

				Toast.makeText(
						New_User_Registration.this,
						"Registration is successful. Please check your email to find your initial password.",
						Toast.LENGTH_LONG).show();
				Intent myIntent = new Intent(New_User_Registration.this,
						Home.class);
				startActivity(myIntent);
			} else if (returnResult.contains("insert_new_user_failed")) {
				Toast.makeText(New_User_Registration.this,
						"Can not create new user. Please try again",
						Toast.LENGTH_SHORT).show();
			} else if (returnResult.contains("existing_user")) {
				Toast.makeText(New_User_Registration.this,
						"This account already exist.", Toast.LENGTH_SHORT)
						.show();
			} else {
				Toast.makeText(New_User_Registration.this, "Network Error",
						Toast.LENGTH_SHORT).show();
			}
		}
	};

	private class ProgressThread extends Thread {
		Handler mHandler;
		String username;
		String phoneNum;

		ProgressThread(Handler h, String name, String phone) {
			mHandler = h;
			username = name;
			phoneNum = phone;
		}

		@Override
		public void run() {
			List<NameValuePair> params = new ArrayList<NameValuePair>(2);
			params.add(new BasicNameValuePair("username", username));
			params.add(new BasicNameValuePair("phonenumber", phoneNum));
			String returnResult = NetworkUtility
					.sendHTTP(params,
							"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/registration.jsp");
			Message msg = mHandler.obtainMessage();
			Bundle b = new Bundle();
			b.putString("returnResult", returnResult);
			msg.setData(b);
			mHandler.sendMessage(msg);

		}
	}

	private boolean missing_info() {
		if (account.getText().toString().matches("")
				|| phoneNum.getText().toString().matches(""))
			return true;
		else
			return false;
	}

	private boolean checkEmailAddress(String str) {

		String at = "@";
		String dot = ".";
		Integer leng = str.length();
		Integer indAt = str.indexOf(at);
		Integer indDot = str.indexOf(dot);

		if (indAt == -1 || indAt == 0 || indAt == leng)
			return false;

		if (indDot == -1 || indDot == 0 || indDot == leng)
			return false;

		if (str.indexOf(at, (indAt + 1)) != -1)
			return false;

		if (str.substring(indAt - 1, indAt) == dot
				|| str.substring(indAt + 1, indAt + 2) == dot)
			return false;

		if (str.indexOf(dot, (indAt + 2)) == -1)
			return false;

		if (str.indexOf(" ") != -1)
			return false;

		return true;
	}
	


}
